<template>
  <div class="app-container">
    <!-- <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
</el-table-column>
<el-table-column label="Title">
  <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
</el-table-column>
<el-table-column label="Author" width="110" align="center">
  <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
</el-table-column>
<el-table-column label="Pageviews" width="110" align="center">
  <template slot-scope="scope">
          {{ scope.row.pageviews }}
        </template>
</el-table-column>
<el-table-column class-name="status-col" label="Status" width="110" align="center">
  <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status }}</el-tag>
        </template>
</el-table-column>
<el-table-column align="center" prop="created_at" label="Display_time" width="200">
  <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.display_time }}</span>
        </template>
</el-table-column>
</el-table> -->
    <!--  功能区域 -->
    <el-form ref="form" :inline="true" :model="form" label-width="80px">
      <el-form-item label="姓名">
        <el-input v-model="form.keyword" placeholder="请输入姓名" clearable></el-input>
      </el-form-item>
      <!-- <el-form-item label="学号">
        <el-input v-model="form.studentId" placeholder="请输入学号" clearable></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="form.phone" placeholder="请输入手机号" clearable></el-input>
      </el-form-item> -->
      <el-form-item label="学院">
        <el-input v-model="form.department" placeholder="请输入学院" clearable></el-input>
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="form.role" placeholder="选择角色" clearable>
          <el-option label="学生" value="STUDENT"></el-option>
          <el-option label="教师" value="TEACHER"></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="状态">
        <el-select v-model="form.enabled" placeholder="选择状态" clearable>
          <el-option label="启用" :value="true"></el-option>
          <el-option label="禁用" :value="false"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="info" @click="handleReset">重置</el-button>
        <el-button type="success" @click="exportToExcel">导出当前页</el-button>
        <el-button type="warning" @click="exportAllToExcel">导出全部</el-button>
        <el-button type="primary" @click="adduser">添加+</el-button>
      </el-form-item>
    </el-form>


    <el-table :data="list.content" style="width: 100%" element-loading-text="Loading" v-loading="listLoading" border>
      <!-- <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item :label="'开放时间段' + Number(index + 1)" v-for="(item, index) in scope.row.availableTimeSlots"
              :key="item.id">
              <span>{{ scope.row.availableTimeSlots[index].startTime | trimSeconds }} -- {{
                scope.row.availableTimeSlots[index].endTime | trimSeconds }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column> -->
      <el-table-column prop="name" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="studentId" label="学号" width="180">
      </el-table-column>
      <el-table-column prop="phone" label="手机号">
      </el-table-column>
      <el-table-column prop="username" label="账号">
      </el-table-column>
      <el-table-column prop="department" label="学院">
      </el-table-column>
      <el-table-column prop="role" label="角色">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <span>{{ scope.row.role === 'TEACHER' ? '教师' : '学生' }}</span>
            <el-switch
              v-model="scope.row.enabled"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="可访问"
              inactive-text="禁止访问"
              @change="handleStatusChange(scope.row)"
            >
            </el-switch>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="examine(scope.$index, scope.row)">编辑</el-button>
          <!-- <el-button type="primary" size="mini" @click="subscribe(scope.$index, scope.row)">预约</el-button> -->
          <!-- <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
          <el-button type="danger" size="mini" @click="deluser(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]" :page-size="pages.size" layout="total, sizes, prev, pager, next, jumper" :total="list.totalElements || 0">
    </el-pagination>

    <!-- 查看弹框1 -->
    <el-dialog title="编辑用户信息" :visible.sync="dialogVisible" width="60%">
      <div>{{ items.name }}</div>
      <!-- 编辑用户信息表单 -->
      <el-form ref="form" :model="items" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="items.name"></el-input>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="items.studentId"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="items.phone"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="items.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="items.password"></el-input>
        </el-form-item>
        <el-form-item label="学院">
          <el-input v-model="items.department"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="items.role"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="updateusers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 预约弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible2" width="60%">
      <!-- 创建用户表单 -->
      <el-form ref="form" :model="forms" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="forms.name"></el-input>
        </el-form-item>
        <el-form-item label="学号">
          <el-input v-model="forms.studentId"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="forms.phone"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="forms.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="forms.password"></el-input>
        </el-form-item>
        <el-form-item label="学院">
          <el-input v-model="forms.department"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="subscribet">创 建</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getList, getEquipmentList, getTimerList, reservations } from '@/api/table'
import { getUserList, updateUser, deleteUser, createUser, updateUserStatus } from '@/api/Teacher'
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: { content: [] },
      listLoading: true,
      form: {
        name: '',
        studentId: '',
        phone: '',
        department: '',
        role: '',
        enabled: ''
      },
      forms: {
        role: "STUDENT",
      },
      currentPage: 1,
      pages: {
        page: 0,
        size: 10,
        role: 'STUDENT'
      },
      dialogVisible: false,
      dialogVisible2: false,
      items: {},
      //设备列表
      equipmentList: [],
      //可预约时间段
      timerList: []
    }
  },
  created() {
    this.fetchData()
  },
  filters: {
    trimSeconds(timeString) {
      // console.log(timeString.replace(/^(\d{2}:\d{2})(:\d{2}(\.\d+)?)?$/, '$1'));
      if (!timeString) return '';
      return timeString.replace(/^(\d{2}:\d{2})(:\d{2}(\.\d+)?)?$/, '$1');
    },
    // 相同的过滤
    dayOf(day) {
      // 遍历day，将day.dayOfWeek中相同的过滤掉只返回不同的
      let dayOfWeek = [];
      if (day.length === 0) return '';
      for (let i = 0; i < day.length; i++) {
        if (dayOfWeek.indexOf(day[i].dayOfWeek) === -1) {
          dayOfWeek.push(day[i].dayOfWeek);
        }
      }
      return dayOfWeek.join(',');
    }
  },
  methods: {
    fetchData() {
      this.listLoading = true
      // 合并分页参数和查询参数
      const params = {
        ...this.pages,
        ...this.form
      };
      // 移除空值参数
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key];
        }
      });
      
      getUserList(params).then(response => {
        this.list = response.data
        this.listLoading = false
        console.log(this.list);
      }).catch(error => {
        this.listLoading = false
        console.error('获取数据失败:', error);
        this.$message.error('获取数据失败');
      })
    },
    // 更新用户信息
    updateusers() {
      console.log(this.items);
      let newuser = {
        name: this.items.name,
        studentId: this.items.studentId,
        phone: this.items.phone,
        username: this.items.username,
        password: this.items.password,
        department: this.items.department,
        role: this.items.role,
        enabled: this.items.enabled
      }
      updateUser(this.items.id, newuser).then(res => {
        this.$message.success('更新用户信息成功');
        this.dialogVisible = false; // 关闭弹框
        this.fetchData(); // 刷新列表
      }).catch(error => {
        console.error('更新用户信息失败:', error);
        this.$message.error('更新用户信息失败，请重试');
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pages.size = val;
      this.pages.page = 0; // 重置到第一页
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.pages.page = val - 1; // 后端从0开始，前端从1开始
      this.fetchData();
    },
    // 查看按钮
    examine(index, row) {
      this.dialogVisible = true;
      this.items = row;
      console.log(index, row);
    },
    // 预约按钮
    subscribe(index, row) {
      this.dialogVisible2 = true;
      this.forms.laboratoryId = row.id
      getEquipmentList(row.id).then(res => {
        this.equipmentList = res.data;
        console.log('实验室设备', res);
      })
      getTimerList(row.id).then(res => {
        this.timerList = res.data;
        console.log('可预约时间段', res.data);
      })
      this.items = row;
      console.log(index, row);
    },
    // 判断选中的事件与预约时间是否冲突
    breaktime(val) {
      const date = new Date(val);
      console.log(date.getDay());
      const dayOfWeek = date.getDay();
      const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
      const weekdayStr = weekdays[dayOfWeek];

      if (!this.forms.timeSlotId) {
        this.$message.error('请先选择时间段');
        this.forms.reservationDate = '';
        return;
      }
      for (let i = 0; i < this.timerList.length; i++) {
        if (this.timerList[i].id === this.forms.timeSlotId) {
          if (this.timerList[i].dayOfWeek !== weekdayStr) {
            this.$message.error('所选时间段与日期不匹配');
            this.forms.reservationDate = '';
            return;
          }
        }


      }
    },
    // 新增用户
    subscribet() {
      console.log(this.forms);
      createUser(this.forms).then(res => {
        this.$message.success('创建用户成功');
        this.dialogVisible2 = false; // 关闭弹框
        this.fetchData(); // 刷新列表
        // 重置表单
        this.forms = {
          role: "STUDENT",
        };
      }).catch(error => {
        console.error('创建用户失败:', error);
        this.$message.error('创建用户失败，请重试');
      });
    },
    // 删除用户按钮
    deluser(index, row) {
      this.$confirm('确定要删除这个用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(row.id).then(res => {
          console.log(res);
          this.$message.success('删除用户成功');
          this.fetchData(); // 刷新列表
        }).catch(error => {
          console.error('删除用户失败:', error);
          this.$message.error('删除用户失败，请重试');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 添加用户按钮
    adduser() {
      this.dialogVisible2 = true;
    },
    handleStatusChange(row) {
      // 处理状态变化的逻辑
      console.log('状态变化', row);
      const statusData = {
        enabled: row.enabled
      };
      
      updateUserStatus(row.id, statusData).then(res => {
        this.$message.success(`用户状态已${row.enabled ? '启用' : '禁用'}`);
        console.log('状态更新成功', res);
      }).catch(error => {
        // 如果更新失败，恢复原来的状态
        row.enabled = !row.enabled;
        this.$message.error('状态更新失败');
        console.error('状态更新失败', error);
      });
    },
    handleSearch() {
      // 实现查询逻辑
      this.pages.page = 0;
      this.currentPage = 1;
      this.fetchData();
    },
    handleReset() {
      // 重置查询条件
      this.form = {
        name: '',
        studentId: '',
        phone: '',
        department: '',
        role: '',
        enabled: ''
      };
      // 重置分页
      this.pages.page = 0;
      this.currentPage = 1;
      // 重新获取数据
      this.fetchData();
    },
    exportToExcel() {
      // 导出当前页Excel功能
      if (!this.list.content || this.list.content.length === 0) {
        this.$message.warning('没有数据可导出');
        return;
      }

      // 准备导出数据
      const exportData = this.list.content.map(item => ({
        '姓名': item.name || '',
        '学号': item.studentId || '',
        '手机号': item.phone || '',
        '账号': item.username || '',
        '学院': item.department || '',
        '角色': item.role || '',
        '状态': item.enabled ? '启用' : '禁用'
      }));

      // 创建工作表
      const worksheet = XLSX.utils.json_to_sheet(exportData);
      
      // 设置列宽
      const columnWidths = [
        { wch: 10 }, // 姓名
        { wch: 15 }, // 学号
        { wch: 15 }, // 手机号
        { wch: 15 }, // 账号
        { wch: 20 }, // 学院
        { wch: 10 }, // 角色
        { wch: 10 }  // 状态
      ];
      worksheet['!cols'] = columnWidths;

      // 创建工作簿
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, '学生信息');

      // 生成文件名（包含当前时间）
      const now = new Date();
      const timestamp = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
      const fileName = `学生信息_${timestamp}.xlsx`;

      // 导出文件
      const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      FileSaver.saveAs(blob, fileName);

      this.$message.success('导出成功');
    },
    exportAllToExcel() {
      // 导出全部数据功能
      this.$confirm('确定要导出全部学生信息吗？这可能需要一些时间。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportAllData();
      }).catch(() => {
        this.$message.info('已取消导出');
      });
    },
    async exportAllData() {
      try {
        this.$message.info('正在获取全部数据，请稍候...');
        
        // 获取所有数据（不分页）
        const allDataParams = {
          page: 0,
          size: 10000, // 设置一个很大的数字来获取所有数据
          role: this.pages.role
        };
        
        const response = await getUserList(allDataParams);
        const allData = response.data.content || [];
        
        if (allData.length === 0) {
          this.$message.warning('没有数据可导出');
          return;
        }

        // 准备导出数据
        const exportData = allData.map(item => ({
          '姓名': item.name || '',
          '学号': item.studentId || '',
          '手机号': item.phone || '',
          '账号': item.username || '',
          '学院': item.department || '',
          '角色': item.role || '',
          '状态': item.enabled ? '启用' : '禁用'
        }));

        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(exportData);
        
        // 设置列宽
        const columnWidths = [
          { wch: 10 }, // 姓名
          { wch: 15 }, // 学号
          { wch: 15 }, // 手机号
          { wch: 15 }, // 账号
          { wch: 20 }, // 学院
          { wch: 10 }, // 角色
          { wch: 10 }  // 状态
        ];
        worksheet['!cols'] = columnWidths;

        // 创建工作簿
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '全部学生信息');

        // 生成文件名（包含当前时间）
        const now = new Date();
        const timestamp = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
        const fileName = `全部学生信息_${timestamp}.xlsx`;

        // 导出文件
        const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
        const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        FileSaver.saveAs(blob, fileName);

        this.$message.success(`导出成功，共导出 ${allData.length} 条记录`);
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请重试');
      }
    }
  }
}
</script>
